{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "<h1> 2d. Distributed training and monitoring </h1>\n",
    "\n",
    "In this notebook, we refactor to call ```train_and_evaluate``` instead of hand-coding our ML pipeline. This allows us to carry out evaluation as part of our training loop instead of as a separate step. It also adds in failure-handling that is necessary for distributed training capabilities.\n"
   ]
  },
  {
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
 "!sudo chown -R jupyter:jupyter /home/jupyter/training-data-analyst"
   ]
  },
  {

"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
 "# Ensure the right version of Tensorflow is installed.\n",
 "!pip freeze | grep tensorflow==2.5"
 ]
},
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "from google.cloud import bigquery\n",
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "import shutil\n",
    "print(tf.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "<h2> Input </h2>\n",
    "\n",
    "Read data created in Lab1a, but this time make it more general, so that we are reading in batches.  Instead of using Pandas, we will use add a filename queue to the TensorFlow graph."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "CSV_COLUMNS = ['fare_amount', 'pickuplon','pickuplat','dropofflon','dropofflat','passengers', 'key']\n",
    "LABEL_COLUMN = 'fare_amount'\n",
    "DEFAULTS = [[0.0], [-74.0], [40.0], [-74.0], [40.7], [1.0], ['nokey']]\n",
    "\n",
    "def read_dataset(filename, mode, batch_size = 512):\n",
    "      def decode_csv(value_column):\n",
    "          columns = tf.compat.v1.decode_csv(value_column, record_defaults = DEFAULTS)\n",
    "          features = dict(zip(CSV_COLUMNS, columns))\n",
    "          label = features.pop(LABEL_COLUMN)\n",
    "          # No need to features.pop('key') since it is not specified in the INPUT_COLUMNS.\n",
    "          # The key passes through the graph unused.\n",
    "          return features, label\n",
    "\n",
    "      # Create list of file names that match \"glob\" pattern (i.e. data_file_*.csv)\n",
    "      filenames_dataset = tf.data.Dataset.list_files(filename)\n",
    "      # Read lines from text files\n",
    "      textlines_dataset = filenames_dataset.flat_map(tf.data.TextLineDataset)\n",
    "      # Parse text lines as comma-separated values (CSV)\n",
    "      dataset = textlines_dataset.map(decode_csv)\n",
    "\n",
    "      # Note:\n",
    "      # use tf.data.Dataset.flat_map to apply one to many transformations (here: filename -> text lines)\n",
    "      # use tf.data.Dataset.map      to apply one to one  transformations (here: text line -> feature list)\n",
    "\n",
    "      if mode == tf.estimator.ModeKeys.TRAIN:\n",
    "          num_epochs = None # indefinitely\n",
    "          dataset = dataset.shuffle(buffer_size = 10 * batch_size)\n",
    "      else:\n",
    "          num_epochs = 1 # end-of-input after this\n",
    "\n",
    "      dataset = dataset.repeat(num_epochs).batch(batch_size)\n",
    "      \n",
    "      return dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "<h2> Create features out of input data </h2>\n",
    "\n",
    "For now, pass these through.  (same as previous lab)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "INPUT_COLUMNS = [\n",
    "    tf.feature_column.numeric_column('pickuplon'),\n",
    "    tf.feature_column.numeric_column('pickuplat'),\n",
    "    tf.feature_column.numeric_column('dropofflat'),\n",
    "    tf.feature_column.numeric_column('dropofflon'),\n",
    "    tf.feature_column.numeric_column('passengers'),\n",
    "]\n",
    "\n",
    "def add_more_features(feats):\n",
    "    # Nothing to add (yet!)\n",
    "    return feats\n",
    "\n",
    "feature_cols = add_more_features(INPUT_COLUMNS)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "<h2> Serving input function </h2>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "# Defines the expected shape of the JSON feed that the model\n",
    "# will receive once deployed behind a REST API in production.\n",
    "def serving_input_fn():\n",
    "    json_feature_placeholders = {\n",
    "        'pickuplon' : tf.compat.v1.placeholder(tf.float32, [None]),\n",
    "        'pickuplat' : tf.compat.v1.placeholder(tf.float32, [None]),\n",
    "        'dropofflat' : tf.compat.v1.placeholder(tf.float32, [None]),\n",
    "        'dropofflon' : tf.compat.v1.placeholder(tf.float32, [None]),\n",
    "        'passengers' : tf.compat.v1.placeholder(tf.float32, [None]),\n",
    "    }\n",
    "    # You can transforma data here from the input format to the format expected by your model.\n",
    "    features = json_feature_placeholders # no transformation needed\n",
    "    return tf.estimator.export.ServingInputReceiver(features, json_feature_placeholders)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "<h2> tf.estimator.train_and_evaluate </h2>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "def train_and_evaluate(output_dir, num_train_steps):\n",
    "    estimator = tf.estimator.LinearRegressor(\n",
    "                       model_dir = output_dir,\n",
    "                       feature_columns = feature_cols)\n",
    "    \n",
    "    train_spec=tf.estimator.TrainSpec(\n",
    "                       input_fn = lambda: read_dataset('./taxi-train.csv', mode = tf.estimator.ModeKeys.TRAIN),\n",
    "                       max_steps = num_train_steps)\n",
    "\n",
    "    exporter = tf.estimator.LatestExporter('exporter', serving_input_fn)\n",
    "\n",
    "    eval_spec=tf.estimator.EvalSpec(\n",
    "                       input_fn = lambda: read_dataset('./taxi-valid.csv', mode = tf.estimator.ModeKeys.EVAL),\n",
    "                       steps = None,\n",
    "                       start_delay_secs = 1, # start evaluating after N seconds\n",
    "                       throttle_secs = 10,  # evaluate every N seconds\n",
    "                       exporters = exporter)\n",
    "    \n",
    "    tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "<h2>Run training</h2>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false,
    "deletable": true,
    "editable": true
   },
   "outputs": [],
   "source": [
    "OUTDIR = './taxi_trained'\n",
    "shutil.rmtree(OUTDIR, ignore_errors = True) # start fresh each time\n",
    "tf.compat.v1.summary.FileWriterCache.clear()\n",
    "train_and_evaluate(OUTDIR, num_train_steps = 500)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "## Challenge Exercise\n",
    "\n",
    "Modify your solution to the challenge exercise in c_dataset.ipynb appropriately."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "deletable": true,
    "editable": true
   },
   "source": [
    "Copyright 2020 Google Inc. Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
